
#include "tasksendpost.h"
#include "log.h"

namespace Wishmaster
{
	class TaskSendPostImpl
	{
	friend class TaskSendPost;
	public:
		TaskSendPostImpl(const PostDescriptor& post, const QString& captcha, Wishmaster2::Network::RequestManager* requestManager) :
			m_post(post), m_captcha(captcha), m_requestManager(requestManager)
		{
		}

		PostDescriptor post() const
		{
			return m_post;
		}

		QString captcha() const
		{
			return m_captcha;
		}

		Wishmaster2::Network::RequestManager* requestManager() const
		{
			return m_requestManager;
		}

		Wishmaster2::Network::RequestPtr request() const
		{
			return m_request;
		}

	private:
		Wishmaster2::Network::RequestPtr m_request;
		PostDescriptor m_post;
		QString m_captcha;
		Wishmaster2::Network::RequestManager* m_requestManager;
	};

	TaskSendPost::TaskSendPost(const PostDescriptor& post, const QString& captcha, Wishmaster2::Network::RequestManager* requestManager, const QString& msg) : Task(msg)
	{
		m_impl = new TaskSendPostImpl(post, captcha, requestManager);
	}

	TaskSendPost::~TaskSendPost()
	{
		delete m_impl;
	}

	void TaskSendPost::start()
	{
		Wishmaster2::Network::RequestPtr request = this->makeRequest(m_impl->post(), m_impl->captcha(), m_impl->requestManager());
		m_impl->m_request = request;
		//m_impl->connector()->connectRequest(this, SLOT(slot_result(RequestPtr,QByteArray)), SLOT(slot_progress(int,int)), request);
		request->connectSignalFinished(boost::bind(&TaskSendPost::requestDone, this, _1));
		m_impl->requestManager()->enqueueRequest(request);
		Task::start();
		log(llDebug, "TaskSendPost::start");
	}

	void TaskSendPost::cancel()
	{
		//m_impl->m_request->cancel();
		Task::cancel();
	}

	PostDescriptor TaskSendPost::postDescriptor() const
	{
		return m_impl->post();
	}

	void TaskSendPost::onError()
	{
		Task::onError();
	}

	void TaskSendPost::requestDone(int requestId)
	{
		onRequestDone();
		QByteArray arr(m_impl->request()->content()->data(), m_impl->request()->content()->size());
		emit result(this, arr, QString::fromStdString(m_impl->request()->contentType()));
		emit done(id());
	}

	void TaskSendPost::slot_progress(int done, int total)
	{
		setPercentage((double)done / total * 100.);
		emit progress(id(), done, total);
	}

	void TaskSendPost::onRequestDone()
	{

	}
}

